package com.td.framework.utils;

import java.security.MessageDigest;
import java.sql.Clob;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.SystemException;

import oracle.sql.CLOB;

/**
 * 
 * Title: 字符串工具类
 * Description:实现对字符串的操作
 * Copyright: Copyright (c) 2008
 * Company 北京水软科技有限公司
 *
 * @author　FLT003
 * @version 1.0
 */
public abstract class StringUtils {

	/**
	 * 将字符串按指定的"分割符"分割成数值数组
	 * 
	 * @param s
	 * @param delim
	 * @return
	 */
	public static int[] splitToIntArray(String s, String delim) {
		String[] stringValueArray = split(s, delim);
		int[] intValueArray = new int[stringValueArray.length];
		for (int i = 0; i < intValueArray.length; i++) {
			intValueArray[i] = Integer.parseInt(stringValueArray[i]);
		}
		return intValueArray;
	}
	
	/**
	 * 获得字符串中,指定分割符号的最后一段 可以用于获得类名 Unqualify a string qualified by a '.' dot
	 * character. For example, "this.name.is.qualified", returns "qualified".
	 * 
	 * @param qualifiedName
	 *            the qualified name
	 */
	public static String unqualify(String qualifiedName) {
		return unqualify(qualifiedName, '.');
	}

	/**
	 * 获得字符串中,指定分割符号的最后一段 可以用于获得文件路径中的路径名称 Unqualify a string qualified by a
	 * separator character. For example, "this:name:is:qualified" returns
	 * "qualified" if using a ':' separator.
	 * 
	 * @param qualifiedName
	 *            the qualified name
	 * @param separator
	 *            the separator
	 */
	public static String unqualify(String qualifiedName, char separator) {
		return qualifiedName
				.substring(qualifiedName.lastIndexOf(separator) + 1);
	}
	
	/**
	 * 把第一个字符变小写 Uncapitalize a <code>String</code>, changing the first
	 * letter to lower case as per {@link Character#toLowerCase(char)}. No
	 * other letters are changed.
	 * 
	 * @param str
	 *            the String to uncapitalize, may be null
	 * @return the uncapitalized String, <code>null</code> if null
	 */
	public static String uncapitalizeFirst(String str) {
		return changeFirstCharacterCase(false, str);
	}

	private static String changeFirstCharacterCase(boolean capitalize,
			String str) {
		int strLen;
		if (str == null || (strLen = str.length()) == 0) {
			return str;
		}
		StringBuffer buf = new StringBuffer(strLen);
		if (capitalize) {
			buf.append(Character.toUpperCase(str.charAt(0)));
		} else {
			buf.append(Character.toLowerCase(str.charAt(0)));
		}
		buf.append(str.substring(1));
		return buf.toString();
	}
	
	/**
	 * 验证字符串是否有文本 当字符串为"null"或"NULL"返回值是false 当字符串为空格返回值是false Check if a String	
	 * @param str the String to check, may be null
	 * @return <code>true</code> if the String is not null, length > 0,
	 * and not whitespace only
	 */
	public static boolean hasText(String str) {
		int strLen;
		if (str == null || (strLen = str.length()) == 0
				|| "null".equals(str.toLowerCase())) {
			return false;
		}
		for (int i = 0; i < strLen; i++) {
			if (!Character.isWhitespace(str.charAt(i))) {
				return true;
			}
		}
		return false;
	}

	
	/**
	 * 效验字符串是否不为空
	 * @param value
	 * @return true 表示 value不为空(value!=null && !"".equals(value))
	 */
	public static boolean isNotNull(String value) {
		return hasLength(value);
	}
	
	/**
	 * 验证字符串是否有长度 当字符串为"null"或"NULL"返回值是false 当字符串为空格返回值是true Check if a String
	 * has length.
	 * @param str
	 *            the String to check, may be null
	 * @return <code>true</code> if the String is not null and has length
	 */
	public static boolean hasLength(String str) {
		return (str != null && str.length() > 0 && !"null".equals(str
				.toLowerCase()));
	}

    /**
     * 中文转换
     * @param source
     * @return
     */
    public static String[] getGBK(String[] source) {
        if (source == null) {
            return null;
        }
        String[] buffer = new String[source.length];
        for (int i = 0; i < source.length; i++) {
            buffer[i] = getGBK(source[i]);
        }
        return buffer;
    }

    public static String getGBK(String source) {
        if (source == null) {
            return null;
        }
        String target = null;
        try {
            byte[] b = source.getBytes("ISO8859_1");
            target = new String(b, "GBK");
        }
        catch (Exception e) {}
        return target;
    }

    public static String[] getISO8859_1(String[] source) {
        String[] buffer = new String[source.length];
        for (int i = 0; i < source.length; i++) {
            buffer[i] = getISO8859_1(source[i]);
        }
        return buffer;
    }

    public static String getISO8859_1(String source) {
        String target = null;
        try {
            byte[] b = source.getBytes("GBK");
            target = new String(b, "ISO8859_1");
        }
        catch (Exception e) {}
        return target;
    }

    /**
     * 字符串替换
     * @param mainStr
     * @param oldStr
     * @param newStr
     * @return
     */
    public static String replace(String mainStr, String oldStr, String newStr) {
        StringBuffer buffer = new StringBuffer(mainStr);
        int index = 0;
        int begin = 0;
        while ( (index = buffer.toString().indexOf(oldStr, begin)) > -1) {
            buffer.replace(index, index + oldStr.length(), newStr);
            begin = index + newStr.length();
        }
        return buffer.toString();
    }

    /**
     * 用于对象的类型转换
     * @param type
     * @param var
     * @return
     * @throws SystemException
     */
    @SuppressWarnings("unchecked")
	public static Object convert(Class type, String var) throws SystemException {
        if (type.getName().equalsIgnoreCase("java.lang.String")) {
            return var;
        }
        else if (type.getName().equalsIgnoreCase("java.math.BigDecimal")) {
            return new java.math.BigDecimal(var);
        }
        else if (type.getName().equalsIgnoreCase("java.sql.Date") ||
                 type.getName().equalsIgnoreCase("java.util.Date")) {
            try {
                return new SimpleDateFormat("yyyy-MM-dd").parse(var);
            }
            catch (ParseException e) {
                throw new SystemException();
            }
        }
        else if (type.getName().equalsIgnoreCase("java.lang.Long") ||
                 type.getName().equalsIgnoreCase("long")) {
            return new java.lang.Long(var);
        }
        else if (type.getName().equalsIgnoreCase("java.lang.Integer") ||
                 type.getName().equalsIgnoreCase("int")) {
            return new java.lang.Integer(var);
        }
        else if (type.getName().equalsIgnoreCase("java.lang.Boolean") ||
                 type.getName().equalsIgnoreCase("boolean")) {
            return new java.lang.Boolean(var);
        }
        else {
            return null;
        }
    }

    /**
     * 字符串是否包含在字符数组中
     * @param value
     * @param array
     * @return
     */
    public static boolean contains(String value, String[] array) {
        if (array != null) {
            for (int i = 0; i < array.length; ++i) {
                if (value != null && array[i] != null && array[i].equals(value)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 加密
     * @param str
     * @return
     */
    public static String crypt(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5"); //所用的加密算法
            md.update(str.getBytes());
            byte[] digestArr = md.digest(); //计算摘要,加密
            String aaa = byte2hex(digestArr);
            return aaa;
        }
        catch (Exception e) {
            return "error!";
        }

    }

    /**
     * 加密辅助
     * @param b
     * @return
     */

    public static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            }
            else {
                hs = hs + stmp;
            }
        }
        return hs.toUpperCase();
    }

    /**
     * 生成随机数
     * flag为位数,如flag=8,则生成8位随机数
     * @param flag
     * @return
     */
    public static String getRandom(int flag) {
        int i;
        String randomStr = "";
        for (int j = 1; j < flag; j++) {
            i = (int) (Math.random() * 10);
            randomStr += String.valueOf(i);
        }
        return randomStr;
    }

    /**
     * 字符数组转换成字符串
     * @param array
     * @param token
     * @return
     */
    public static String StringArrayToString(String[] array, String token) {
        if (array != null) {
            String separator = token == null ? "," : token;
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < array.length; i++) {
                if (i > 0) {
                    buffer.append(separator);
                }
                buffer.append(array[i]);
            }
            return buffer.toString();
        }
        return null;
    }

    /**
     * 字符串转换成字符数组
     * @param var
     * @param token
     * @return
     */
    public static String[] StringToStringArray(String var, String token) {
        String separator = token == null ? "," : token;
        if (var != null) {
            StringTokenizer st = new StringTokenizer(var, separator);
            String[] buffer = new String[st.countTokens()];
            int t = 0;
            while (st.hasMoreTokens()) {
                buffer[t] = st.nextToken();
                t++;
            }
            return buffer;
        }
        return null;
    }

    /**
     * 字符串处理，写SQL语句
     * @param strSource
     * @return
     */
    public static String toSqlString(String strSource) {
        String strResult;
        if (strSource == null) {
            strResult = "null";
        }
        else {
            strResult = replace(strSource, "'", "''");
            strResult = replace(strResult, "&lt;", "<");
            strResult = replace(strResult, "&gt;", ">");
            strResult = "'" + strResult + "'";
        }
        return strResult;
    }

    /**
     * 说明:用于html页面中'null'转换
     * @param obj
     * @param str
     * @return
     */
    public static String changeNullToStr(Object obj, String str) {
        if (obj == null || obj.toString().equals("null")) {
            return str;
        }
        else {
            return obj.toString();
        }
    }

    /**
     * 说明:用于html页面中'null'转换为""
     * @param obj
     * @return
     */
    public static String changeNullToStr(Object obj) {
        if (obj == null) {
            return "";
        }
        else {
            return obj.toString();
        }
    }

    /**
     * 把字符串第一个字母转换成大写
     * @param str
     * @return
     */
    public static String firstCharToUpperCase(String str) {
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    }

    /**
     * 把字符串第一个字母转换成小写
     * @param str
     * @return
     */
    public static String firstCharToLowerCase(String str) {
        return str.substring(0, 1).toLowerCase() + str.substring(1);
    }

    /**
     * 把字符串转换成clob
     * @param str
     * @return
     * @throws SystemException
     */
    public static Clob converStringToClob(String str) throws SystemException {
        if (str == null) {
            return null;
        }
        try {
            CLOB clob = CLOB.empty_lob();
            clob.setBytes(str.getBytes());
            return clob;
        }
        catch (SQLException e) {
            throw new SystemException();
        }
    }

    /**
     * 把clob转换成字符串
     * @param clob
     * @return
     * @throws SystemException
     */
    public static String converClobToString(Clob clob) throws SystemException {
        CLOB clobvalue = (CLOB) clob;
        if (clob == null) {
            return null;
        }
        byte[] bytes = clobvalue.getBytes();
        return bytes == null ? null : new String(bytes);
    }

    /**
     * 分割字串
     * @param source 原始字符
     * @param div 分割符
     * @return 字符串数组
     */
    public static String[] split(String source, String div) {
        int arynum = 0, intIdx = 0, intIdex = 0, div_length = div.length();
        if (source.compareTo("") != 0) {
            if (source.indexOf(div) != -1) {
                intIdx = source.indexOf(div);
                for (int intCount = 1; ; intCount++) {
                    if (source.indexOf(div, intIdx + div_length) != -1) {
                        intIdx = source.indexOf(div, intIdx + div_length);
                        arynum = intCount;
                    }
                    else {
                        arynum += 2;
                        break;
                    }
                }
            }
            else {
                arynum = 1;
            }
        }
        else {
            arynum = 0;

        }
        intIdx = 0;
        intIdex = 0;
        String[] returnStr = new String[arynum];

        if (source.compareTo("") != 0) {
            if (source.indexOf(div) != -1) {
                intIdx = (int) source.indexOf(div);
                returnStr[0] = (String) source.substring(0, intIdx);
                for (int intCount = 1; ; intCount++) {
                    if (source.indexOf(div, intIdx + div_length) != -1) {
                        intIdex = (int) source.indexOf(div, intIdx + div_length);
                        returnStr[intCount] = (String) source.substring(intIdx +
                            div_length,
                            intIdex);
                        intIdx = (int) source.indexOf(div, intIdx + div_length);
                    }
                    else {
                        returnStr[intCount] = (String) source.substring(intIdx +
                            div_length,
                            source.length());
                        break;
                    }
                }
            }
            else {
                returnStr[0] = (String) source.substring(0, source.length());
                return returnStr;
            }
        }
        else {
            return returnStr;
        }
        return returnStr;
    }

    /**
     * 将字符串格式成html格式
     * @param str 被转换的字符串
     * @return String if str is not null ,otherwise return null
     */
    public static String formatStringToHtml(String str) {
        if (str == null) {
            return "";
        }
        str = replace(str, "\n", "<br>");
        str = replace(str, "\'", "\\\'");
        str = replace(str, "\"", "\\\"");
        str = replace(str, "  ", "&nbsp;");
        return str;
    }

    /**
     * 判断字符串是否为null或者空。
     * @param str 待判断的字符串
     * @return boolean 判断结果
     */
    public static boolean isBlank(String str) {
        return (str == null) || (str.equals(""));
    }

    /**
     * 从HttpServletRequest对象中取字符串数组。
     * @param oRequest HttpServletRequest对象
     * @param strParamName 参数名
     * @param strDefaultValue 默认值
     * @return 字符串数组
     */
    public static String[] getStringArray(
        HttpServletRequest oRequest,
        String strParamName,
        String strDefaultValue) {
        if (oRequest == null || StringUtils.isBlank(strParamName)) {
            return null;
        }
        String[] strParameterValues = oRequest.getParameterValues(strParamName);
        if (strParameterValues == null) {
            strParameterValues = new String[0];
        }
        for (int i = 0; i < strParameterValues.length; i++) {
            if (strParameterValues[i] == null ||
                strParameterValues[i].equals("")) {
                strParameterValues[i] = strDefaultValue;
            }
        }
        return strParameterValues;
    }

 
    /**
     * 从字符串中解析属性，字符串格式为：“”
     * @param initString
     * @return
     */
    @SuppressWarnings("unchecked")
	public static Map ConvertStringToProperties(String initString) {
        HashMap properties = new HashMap();
        if (initString == null) {
            return properties;
        }
        StringTokenizer pst = new StringTokenizer(initString, ";");
        String property = null;
        String name = null;
        String value = null;
        StringTokenizer nst = null;
        while (pst.hasMoreTokens()) {
            property = pst.nextToken();
            nst = new StringTokenizer(property, "=");
            if (nst.countTokens() == 2) {
                name = nst.nextToken().trim().toLowerCase();
                value = nst.nextToken().trim();
                properties.put(name, value);
            }
        }
        return properties;
    }

    /**
     * 把精简格式日期（例：1978-10-21）转化为中文描述（例：1978年10月21日）。
     * 注意：
     * 1、此方法不验证日期正确性
     * 2、dateString还可以适用于只有年月（例：1978-10）或者只有年（例：1978）的情况
     * 3、此方法缺省分隔符为“-”
     * @param dateString 精简格式日期字符串
     * @return 中文日期字符串
     */
    public static String formatDateStringToChinese(String dateString) {
        return formatDateStringToChinese(dateString, "-");
    }

    /**
     * 把精简格式日期（例：1978-10-21）转化为中文描述（例：1978年10月21日）。
     * 注意：
     * 1、此方法不验证日期正确性
     * 2、dateString还可以适用于只有年月（例：1978-10）或者只有年（例：1978）的情况
     * @param dateString 精简格式日期字符串
     * @param separator 分隔符号（例：1978-10-21 分隔符为“-”，1978/10/21 分隔符为“/”）
     * @return 中文日期字符串
     */
    public static String formatDateStringToChinese(String dateString,
        String separator) {
        StringBuffer chinese = null;
        if (dateString != null) {
            StringTokenizer stk = new StringTokenizer(dateString, separator);
            if (stk.hasMoreTokens()) {
                //年
                chinese = new StringBuffer();
                chinese.append(stk.nextToken());
                chinese.append("年");
                if (stk.hasMoreTokens()) {
                    //月
                    chinese.append(stk.nextToken());
                    chinese.append("月");
                    if (stk.hasMoreTokens()) {
                        //日
                        chinese.append(stk.nextToken());
                        chinese.append("日");
                    }
                }

            }
            return chinese.toString();
        }
        return null;
    }

    /**
     * 判断字符串第一个字符是否包含数字
     * @param str
     * @return
     */
    public static boolean isNumber(String str) {
        if ("0123456789".indexOf(str.substring(0, 1)) == -1) {
            return false;
        }
        else {
            return true;
        }
    }

    /**
     * 判断字符串第一个字符是否包含大小写字符
     * @param str
     * @return
     */
    public static boolean isLetter(String str) {
        if ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".indexOf(str.
            substring(0, 1)) ==-1) {
            return false;
        }
        else {
            return true;
        }
    }

    /**
     * 判断字符串第一个字符是否包含特殊符号
     * @param str
     * @return
     */
    public static boolean isSymbol(String str) {
        if ("!@#$%^&*()_+-=|[]{}'\",./?<>\\".indexOf(str.substring(0, 1)) ==
            -1) {
            return false;
        }
        else {
            return true;
        }
    }

    /**
     * 判断字符中是否在数组中
     */
    public static int ArrayIndexOf(String[] array, String str) {
        int index = -1;
        if (array == null) {
            return index;
        }
        for (int i = 0; i < array.length; i++) {
            if (array[i].equals(str)) {
                index = i;
                break;
            }
        }
        return index;
    }


    /**
     * 数字格式化方法,如1格式化为0001
     * @param num  需格式化的数字
     * @param scale 位数
     * @return
     */
    public static String numberFormat(int num, int scale) {
        String formatStr = Integer.toString(num);
        for (int i = formatStr.length(); i < scale; i++) {
            formatStr = "0" + formatStr;
        }
        return formatStr;
    }

    /**
     * 根据出生日期计算年龄
     * @param csrq
     * @return
     */
    public static int birthdayToAge(String csrq) {
        int age = 0;
        int csrq_year = Integer.parseInt(csrq.substring(0, 4));
        int csrq_month = Integer.parseInt(csrq.substring(5, 7));
        int csrq_days = Integer.parseInt(csrq.substring(8, 10));
        String now = getCurrentDate();
        int year = Integer.parseInt(now.substring(0, 4));
        int month = Integer.parseInt(now.substring(5, 7));
        int days = Integer.parseInt(now.substring(8, 10));

        if (now.compareTo(csrq) > 0) {
            if (year != csrq_year) {
                if (month == csrq_month && days == csrq_days) {
                    age = year - csrq_year;
                }
                else if (month != csrq_month) {
                    if (month >= csrq_month) {
                        age = year - csrq_year + 1;
                    }
                    else if (month < csrq_month) {
                        age = year - csrq_year - 1;
                    }
                }
                else if (month == csrq_month) {
                    if (days >= csrq_days) {
                        age = year - csrq_year + 1;
                    }
                    else if (days < csrq_days) {
                        age = year - csrq_year - 1;
                    }
                }
                return age;
            }
            else if (year == csrq_year) {
                age = 0;
            }
        }
        return age;
    }

    /**
     *
     * @return  当前日期年月日
     */
    public static String getCurrentDate() {
      long now = System.currentTimeMillis();
      java.util.Date CurrTime = new java.util.Date(now);
      SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
      String rq = dateformat.format(CurrTime);
      return rq;
    }
    
    /**
     * toDO:去除字符串中重复的子字符串;
     * @param str 字符串
     * @param split 分隔符
     * @return string
     */
    public static String removeSameString(String str , String split)
    {
		StringBuffer buffer = new StringBuffer();
		Set<String> mLinkedSet = new LinkedHashSet<String>();
		if(split==null)
		{
			split = " ";
		}
		String [] temp = str.split(split);
		for (int i = 0; i < temp.length; i++) {
			if(!mLinkedSet.contains(temp[i]))
			{
				buffer.append(temp[i]+split);
				mLinkedSet.add(temp[i]);
			}
		}
		return buffer.toString();
    }
	
}
